<template>
  <div class="formula-library">
    <el-card>
      <template #header>
        <span>公式库</span>
      </template>

      <el-table
          :data="formulaStore.formulaLibrary.formulas"
          style="width: 100%"
          empty-text="暂无公式，请先创建公式"
      >
        <el-table-column prop="title" label="标题" min-width="150" />
        <el-table-column label="预览" min-width="200">
          <template #default="{ row }">
            <div v-if="row.latex" class="table-preview" v-html="getPreview(row.latex)"></div>
            <span v-else class="no-preview">无内容</span>
          </template>
        </el-table-column>
        <el-table-column prop="updatedAt" label="更新时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.updatedAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button link type="primary" @click="loadFormula(row.id)">
              加载
            </el-button>
            <el-button link type="danger" @click="deleteFormula(row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus';
import katex from 'katex';
import { useFormulaStore } from '../stores/formula';

const formulaStore = useFormulaStore();

const getPreview = (latex: string) => {
  try {
    return katex.renderToString(latex, {
      throwOnError: false,
      displayMode: false
    });
  } catch {
    return '<span style="color: #f56c6c;">渲染错误</span>';
  }
};

const formatTime = (timestamp: number) => {
  return new Date(timestamp).toLocaleString();
};

const loadFormula = (id: string) => {
  formulaStore.loadFormula(id);
  ElMessage.success('公式加载成功');
};

const deleteFormula = async (id: string) => {
  try {
    await ElMessageBox.confirm(
        '确定要删除这个公式吗？',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    );

    formulaStore.deleteFormula(id);
    ElMessage.success('公式删除成功');
  } catch {
    // 用户取消删除
  }
};
</script>

<style scoped>
.table-preview {
  font-size: 0.9em;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.no-preview {
  color: #c0c4cc;
}
</style>
